//
//  AppDelegate.m
//  YLHelper
//
//  Created by she1323 on 2018/3/26.
//  Copyright © 2018年 she1323. All rights reserved.
//



#import "AppDelegate.h"
#import "YLUserViewController.h"
#import "LKTabbarControllerConfig.h"
#import "CYLPlusButtonSubClass.h"
#import "LKSwitchRootVcTool.h"
#import "LKUserInforTool.h"
#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import "LaunchIntroductionView.h"
#import "YLPushViewModel.h"
#import "XHVersion.h"
#define APPKEY @"5ad94391f43e480c0e0000e1"

#define WeChatKey @"wx2181059ab93c83b3"
#define WeChatSecrect @""
#define QQKey @"1106782394"
#define QQSecrect @"p0wMAFaVEGp3mEuM"


// iOS10注册APNs所需头文件

//#define pushAppkey @"eda9a06ff04e87e13f24a30d"

#define pushAppkey @"2f1fa6008fa81cbb9aa5f077"


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [XHVersion checkNewVersion];
    
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    self.window.backgroundColor = [UIColor whiteColor];
    
    [LKSwitchRootVcTool switchRootController];
    [self.window makeKeyAndVisible];
    NSArray *images = @[@"launch1",@"launch2",@"launch3", @"launch4"];
    LaunchIntroductionView *launch = [LaunchIntroductionView sharedWithImages:images buttonImage:@"" buttonFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    launch.currentColor = [UIColor clearColor];
    launch.nomalColor = [UIColor clearColor];
    

    
    
    /****************************友盟登录的设置****************************************/
    /* 打开日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    // 打开图片水印
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    [UMSocialGlobal shareInstance].isClearCacheWhenGetUserInfo = NO;
    /* 设置友盟appkey */
//    [[UMSocialManager defaultManager] setUmSocialAppkey:APPKEY];
    [UMConfigure initWithAppkey:APPKEY channel:@"App Store"];
//    [UMSocialManager defaultManager]
    [self setNavgationBarStyle];
    [self confitUShareSettings];
    [self configUSharePlatforms];
    
    // 注册APNS
    [self initAPNS];
    // 初始化push
    [self initPush:launchOptions];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
    return YES;
}
// 接收到通知事件
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSLog(@"接受到的信息数据%@",userInfo);
    [YLPushViewModel setNewTagsWithInfo:userInfo];
}
- (void)initAPNS
{
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        if (@available(iOS 10.0, *)) {
            entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        } else {
            // Fallback on earlier versions
        }
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
}

- (void)initPush:(NSDictionary *)launchOptions
{
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:pushAppkey
                          channel:nil
                 apsForProduction:NO
            advertisingIdentifier:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}
// 当应用在前台运行中，收到远程通知时，会回调这个方法。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark - 通知相关
#pragma mark 在前台接受到通知会调用 / 当应用在后台状态时，点击push消息启动应用 (ios10在前台接收到不会调用)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 取得 APNs 标准信息内容
    
    //BOOL isActive;
    if (application.applicationState == UIApplicationStateActive) {
        //  isActive = YES;
    } else {
        //  isActive = NO;
        [self jumpToOther:userInfo];
    }
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)jumpToOther:(NSDictionary *)userInfo
{
    // 得到通知的内容
    [YLPushViewModel pushWithInfo:userInfo];
}

// 添加处理APNs通知回调方法
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
// iOS 10 在前台收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    } // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}


// iOS 10 Support
// App通知的点击事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self jumpToOther:userInfo];
    
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler();  // 系统要求执行这个方法
}


// 当客户端注册远程通知时，如果成功，则回调第一个，客户端把deviceToken取出来发给服务端，push消息的时候要用。
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [YLPushViewModel setUpMyPushInfo];
    [JPUSHService registerDeviceToken:deviceToken];
}

/**
 设置导航栏的全局变量颜色
 */
-(void)setNavgationBarStyle{
    //设置导航条颜色 美团导航栏颜色
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    
    //设置导航条文字颜色 白色
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:COLOR_HEX(0x000000)}];
    
    //设置按钮文字颜色 白色
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    
    //设置导航栏按钮字体大小
    [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:18], UITextAttributeFont,nil] forState:UIControlStateNormal];
}
- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

/**
 配置分享配置
 */
- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WeChatKey appSecret:WeChatSecrect redirectURL:@""];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQKey/*设置QQ平台的appID*/  appSecret:QQSecrect redirectURL:@""];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sms appKey:@"" appSecret:nil redirectURL:@""];
}
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
